import { Text, StyleSheet, View, TouchableOpacity, ActivityIndicator, PermissionsAndroid, Image } from 'react-native'
import React, { useState, useEffect, useCallback } from 'react'
import httpApi from "../../api"
import { Toast } from '@pingtou/rn-vant';
import { pTx } from "../../utils/dimensions"
import { useRealm, useQuery } from '@realm/react'
import { schemaName } from "../../realm"
import { launchImageLibrary } from 'react-native-image-picker';
import Realm from "realm"
import Avatar from "../../components/avatar"

const GroupLogo = (props) => {
    const realm = useRealm();

    const [group] = useState(props.route.params)
    const userInfo = useQuery(schemaName.UserInfo, userInfo => {
        return userInfo.filtered('Current = true');
    })[0];
    const groupInfo = useQuery(schemaName.GroupInfo, Info => {
        return Info.filtered(`Id == ${group.G} and UserId == ${userInfo.Id}`);
    })[0];
    const groupList = useQuery(schemaName.GroupList, list => {
        return list.filtered(`G == ${group.G} and UserId == ${userInfo.Id}`);
    })[0];

    const [loading, setLoading] = useState(false)
    const [groupName, setGroupName] = useState(groupInfo.GroupName)
    const [curFiles, setCurFiles] = useState([])

    const updateGroupInfo = async () => {
        try {
            setLoading(true)
            const image = await httpApi.uploadMinio(curFiles)
            if (!image.data.FileNames[0]) return
            const res = await httpApi.updateGroupInfo({ groupId: group.G, groupLogo: image.data.FileNames[0] })
            if (res.code == 20) {
                realm.write(() => {
                    groupInfo.Logo = image.data.FileNames[0]
                    groupList.L = image.data.FileNames[0]
                })
                props.navigation.goBack()
            } else {
                Toast(res.message)
            }
        } catch (error) {
        }
        setLoading(false)
    }
    const cameraPermission = async () => {
        launchImageLibrary({
            mediaType: 'photo',
            maxWidth: 1000,
            maxHeight: 1000,
            quality: 1,
            videoQuality: 'low',
            includeBase64: true
        }, res => {
            if (res.didCancel) {
                return false;
            } else {
                const curFiles = res.assets
                setCurFiles(curFiles)
            }
        })
    }
    useEffect(() => {
        if (Platform.OS === 'android') {
            try {
                PermissionsAndroid.request(
                    PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
                    {
                        title: '需要访问相册',
                        message: '需要访问相册',
                        buttonPositive: '',
                    },
                ).then(granted => {
                    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
                        // this.setState({
                        //     granted: true,
                        // })
                    } else {
                        // this.setState({
                        //     granted: false,
                        // })
                    }
                })

            } catch (err) {
                console.warn(err)
            }
        }
    }, [])
    return (
        <View style={styles.page}>
            <Text style={styles.title}>修改群头像</Text>
            <View style={styles.ProfilePhotoPopupBox}>
                <TouchableOpacity onPress={() => cameraPermission()}>
                    {
                        curFiles[0]?.uri ? <Image
                            style={styles.ProfilePhotoPopupImage}
                            source={{ uri: curFiles[0]?.uri }} />
                            : <Avatar style={styles.ProfilePhotoPopupImage} source={{ uri: groupInfo.Logo || group.P }}></Avatar>

                    }
                </TouchableOpacity>
            </View>
            <View style={styles.button}>
                <TouchableOpacity disabled={loading || !groupName} onPress={() => updateGroupInfo()}>
                    <Text style={[styles.headText,]}>
                        <>
                            {loading ? <ActivityIndicator /> : "确认"}
                        </>
                    </Text>
                </TouchableOpacity>
            </View>
        </View>
    )
}

export default GroupLogo




const styles = StyleSheet.create({
    page: {
        flex: 1,
        paddingHorizontal: pTx(18),
        paddingVertical: pTx(30),
        backgroundColor: "#fff"
    },
    title: {
        textAlign: "center",
        fontSize: pTx(18),
        color: "#333"

    },
    ProfilePhotoPopupBox: {
        marginTop: pTx(50),
        flexDirection: 'row',
        justifyContent: "center",
    },
    ProfilePhotoPopupImage: {
        width: pTx(200),
        height: pTx(200),
        backgroundColor: "#fff"
    },
    button: {
        marginTop: pTx(40),
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "center"
    },
    headText: {
        width: pTx(180),
        color: "#fff",
        fontSize: pTx(16),
        paddingVertical: pTx(13),
        textAlign: "center",
        backgroundColor: "rgba(6, 193, 97, 1)",
        borderRadius: pTx(12),
    }
})